﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.SharePoint.Client;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using eb = MyData.ExpressionBuilder.Model;

namespace MyDataTestProject
{
  [TestClass]
  public class OfficeOpenXml
  {
    public void CopyStream(Stream source, Stream destination)
    {
      //Temporarily hard-coded value
      byte[] buffer = new byte[32768];
      int bytesRead;
      do
      {
        bytesRead = source.Read(buffer, 0, buffer.Length);
        destination.Write(buffer, 0, bytesRead);
      } while (bytesRead != 0);
    }

    public Stream FileStream(string url, string documentName, string libraryTitle)
    {     
      Stream fileStream = null;
      Dictionary<string, object> fileMetadata = new Dictionary<string, object>();
      FileInformation fileInformation = null;

      using(ClientContext clientContext = new ClientContext(url))
      {
        //WF: clientContext.Credentials = NetworkCredential.Get(context);
        Microsoft.SharePoint.Client.List sharedDocumentsList = clientContext.Web.Lists.GetByTitle(libraryTitle);

        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml =
          @"<View>
              <Query>
                <Where>
                  <Eq>
                    <FieldRef Name='FileLeafRef'/>
                    <Value Type='Text'>" + documentName + @"</Value>
                  </Eq>
                </Where>
                <RowLimit>1</RowLimit>
              </Query>
            </View>";
          Microsoft.SharePoint.Client.ListItemCollection listItems = sharedDocumentsList.GetItems(camlQuery);
          clientContext.Load(sharedDocumentsList);
          clientContext.Load(listItems);
          clientContext.ExecuteQuery();

          if (listItems.Count == 1)
          {
            Microsoft.SharePoint.Client.ListItem item = listItems[0];
            fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, (string)item["FileRef"]);
            fileStream = fileInformation.Stream;
          }       

      }

      return fileStream;
    }

    [TestMethod]
    public void GetContentControlValues()
    {
      string reference = string.Empty;
      string viewName = string.Empty;
      string value = string.Empty;
      WordprocessingDocument wordDocument;
      string url = "http://localhost";
      string documentName = "sample.docx";
      string libraryTitle = "Shared Documents";

      Stream fileStream = this.FileStream(url, documentName, libraryTitle);

      if (fileStream != null)
      {
        using (MemoryStream memoryStream = new MemoryStream())
        {
          //Copy Xml Stream. This version is tightly coupled with Excel. Future versions will decouple to support
          CopyStream(fileStream, memoryStream);

          using (wordDocument = WordprocessingDocument.Open(memoryStream, false))
          {

            IEnumerable<string> contentControlValues = wordDocument.MainDocumentPart.RootElement.Descendants()
              .Where(e => e is SdtBlock || e is SdtRun)
              .Select(e => e.InnerText);

            Assert.IsTrue(contentControlValues.Count() > 0);
          }
        }
      }
    }

    [TestMethod]
    public void GetContentControlNames()
    {

      string url = "http://localhost";
      string documentName = "Project Initiation Checklist.docx";
      string libraryTitle = "Shared Documents";

      Stream fileStream = this.FileStream(url, documentName, libraryTitle);

      if (fileStream != null)
      {
        using (MemoryStream memoryStream = new MemoryStream())
        {
          //Copy Xml Stream. This version is tightly coupled with Excel. Future versions will decouple to support
          CopyStream(fileStream, memoryStream);

          using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(memoryStream, false))
          {
          
            var allTagsTest =
              wordDocument.MainDocumentPart.Document.Body.Descendants()
              .Where(e => e is SdtBlock || e is SdtRun || e is SdtCell)
              .Select(r => r);

            Assert.IsTrue(allTagsTest.Count() > 0);

            IEnumerable<eb.NamedRange> contentControls =
              wordDocument.MainDocumentPart.Document.Body.Descendants()
              .Where(c => c is SdtBlock || c is SdtRun || c is SdtCell)
              .Select(c => 
                  new eb.NamedRange
                  { 
                    Name = c.Descendants<Tag>().FirstOrDefault().Val.ToString(),
                    Value = c.InnerText,
                    ContentPart = c,
                    IsRoot = c.Parent.GetType() == typeof(Body),
                    HasTable = c.Descendants<Table>().FirstOrDefault() == null ? false : true,
                    IsEmbedded = c.Parent.GetType() == typeof(Paragraph)
                  }
             );
            
            Assert.IsTrue(contentControls.Count() > 0);

          }
        }
      }
    }
  }
}

